package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.network.HttpUtil
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentShopNoticeBinding
import com.gexiaobao.pigeon.ui.activity.TestInputActivity
import com.gexiaobao.pigeon.ui.adapter.RecentContactsAdapter
import com.gexiaobao.pigeon.viewmodel.MallImModel
import com.luck.picture.lib.thread.PictureThreadUtils.runOnUiThread
import com.xinbida.wukongim.WKIM
import com.xinbida.wukongim.interfaces.IGetSocketIpAndPortListener
import com.yanzhenjie.recyclerview.OnItemMenuClickListener
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import org.json.JSONException
import org.json.JSONObject

/**
 * @Author      : hxw
 * @Date        : 2024/2/1 14:03
 * @Describe    : 消息
 */
class FragmentNotice : BaseFragment<MallImModel, FragmentShopNoticeBinding>() {

    private var userId: String? = ""
    private var token: String? = ""
    private val mAdapter: RecentContactsAdapter by lazy { RecentContactsAdapter(arrayListOf()) }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        userId = KvUtils.decodeString(Constant.USERID)
        token = CacheUtil.getToken()
        WKIM.getInstance().init(context, userId, token)
        val swipeMenuCreator = SwipeMenuCreator { _, rightMenu, _ ->
            val width = resources.getDimensionPixelSize(R.dimen.dp_70)
            val height = ViewGroup.LayoutParams.MATCH_PARENT
            val deleteItem = SwipeMenuItem(activity)
                .setBackground(R.drawable.round_b_g_5_train_fly_list_delete_red)
                .setTextColor(Color.WHITE)
                .setText(R.string.delete)
                .setTextSize(15)
                .setWidth(width)
                .setHeight(height)
            rightMenu.addMenuItem(deleteItem)
        }
        mDatabind.swipeRvNotice.setSwipeMenuCreator(swipeMenuCreator)

        val mItemMenuClickListener = OnItemMenuClickListener { menuBridge, position ->
            /** 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱 */
            menuBridge.closeMenu()
            /** 调用删除接口 */
            val channelID = mAdapter.data[position].channel_id
            if (channelID != "null" && channelID.isNotEmpty()) {
                deleteRecentContact(channelID.toInt(), mAdapter.data[position].channel_type.toByte(), position)
            }
        }
        mDatabind.swipeRvNotice.setOnItemMenuClickListener(mItemMenuClickListener)

        mDatabind.swipeRvNotice.init(LinearLayoutManager(context), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, 0)
        )

        mAdapter.setOnItemClickListener { _, _, position ->
            chatLogin(1, position)
        }
        addImListener()
    }

    private fun chatLogin(type: Int, position: Int) {
        onStop()
        if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(token)) {
            val jsonObject = JSONObject()
            try {
                jsonObject.put("uid", userId)
                jsonObject.put("token", token)
                jsonObject.put("device_flag", 0)
                jsonObject.put("device_level", 1)
            } catch (e: JSONException) {
                throw RuntimeException(e)
            }
            Thread {
                HttpUtil.getInstance().post("/user/token", jsonObject) { code, _ ->
                    if (code == 200) {
                        LogUtils.debugInfo("FragmentNotice:登录成功")
                        if (type == 0) {
                            /** 连接 */
                            WKIM.getInstance().connectionManager.connection()
                            return@post
                        }
                        startActivity<TestInputActivity>("channelId" to mAdapter.data[position].channel_id, "token" to token!!, "uid" to userId!!)
                    } else {
                        runOnUiThread {
                            RxToast.showToast("登录失败【$code】")
                        }
                    }
                }
            }.start()
        }
    }

    private fun addImListener() {
        /** 连接状态监听 */
        WKIM.getInstance().connectionManager.addOnConnectionStatusListener("main_act") { code: Int, _: String? ->
            LogUtils.debugInfo("addOnConnectionStatusListener----->>$code")
        }

        /** 监听最近会话刷新 */
        WKIM.getInstance().conversationManager.addOnRefreshMsgListener("key") { _, isEnd ->
            /** 1、 wkUIConversationMsg 最近会话消息内容 UI上已有该会话需进行更新，反之添加到UI上
             *  2、isEnd 为了防止频繁刷新UI，当isEnd为true可刷新UI
             */
            if (isEnd)
                getRecentContact()
        }

        WKIM.getInstance().connectionManager.addOnGetIpAndPortListener { andPortListener: IGetSocketIpAndPortListener ->
            Thread {
                HttpUtil.getInstance()["/route", { code: Int, data: String ->
                    if (code == 200) {
                        try {
                            val jsonObject = JSONObject(data)
                            val tcp_addr = jsonObject.optString("tcp_addr")
                            val strings = tcp_addr.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                            Log.e("获取连接的IP", "-->$data")
                            andPortListener.onGetSocketIpAndPort(strings[0], strings[1].toInt())
                        } catch (e: JSONException) {
                            throw RuntimeException(e)
                        }
                    }
                }]
            }.start()
        }
    }

    private fun deleteRecentContact(channelId: Int, channelType: Byte, position: Int) {
        /** 删除某个会话 */
        Thread {
            HttpUtil.getInstance().removeSubscriber(channelId) { isRemove ->
                if (isRemove) {
                    mAdapter.data.removeAt(position)
                    mAdapter.notifyItemRemoved(position)
                }
            }
        }.start()
    }

    override fun onResume() {
        super.onResume()
        chatLogin(0, 0)
        getRecentContact()
    }

    override fun onStop() {
        super.onStop()
        WKIM.getInstance().connectionManager.disconnect(false)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        /** 断开连接 */
        WKIM.getInstance().connectionManager.disconnect(true)
        /** 移除监听最近会话列表 */
        WKIM.getInstance().conversationManager.removeOnRefreshMsgListener("key")
        WKIM.getInstance().connectionManager.removeOnConnectionStatusListener("main_act")
    }

    @SuppressLint("SetTextI18n")
    private fun getRecentContact() {
        showLoading(getString(R.string.loading))
        val uid = KvUtils.decodeString(Constant.USERID)
        try {
            Thread {
                HttpUtil.getInstance().getSyncMessage(uid, 0, "", 10) { list ->
                    dismissLoading()
                    if (list != null && list.size > 0) {
                        runOnUiThread {
                            mAdapter.setList(list)
                            if (list.isNotEmpty()) {
                                var result = 0
                                list.forEach { data ->
                                    result += data.unread
                                    if (result != 0) {
                                        mDatabind.tvNoticeSubTitle.text = result.toString() + "条消息未读"
                                    } else {
                                        mDatabind.tvNoticeSubTitle.text = ""
                                    }
                                }
                            }
                        }
                    } else {
                        mAdapter.setList(ArrayList())
                    }
                }
            }.start()
        } catch (e: NullPointerException) {
            dismissLoading()
            e.printStackTrace()
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.syncResult.observe(viewLifecycleOwner) {

        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.ivNoticeBack) {
            when (it) {
                mDatabind.ivNoticeBack -> {
                    nav().navigateUp()
                }
            }
        }
    }
}